<template>
  <div class="todoapp">
    <TodoHeader @create="createFn" :arr="list"></TodoHeader>
    <TodoMain :arr="showArr" @del="delFn"></TodoMain>
    <TodoFooter :arr="showArr" @changeType="typeFn" @clear='clearFn'></TodoFooter>
  </div>
</template>

<script>
import './styles/index.css'
import './styles/base.css'
import TodoFooter from './components/TodoFooter.vue'
import TodoHeader from './components/TodoHeader.vue'
import TodoMain from './components/TodoMain.vue'
export default {
  components: {
    TodoFooter,
    TodoHeader,
    TodoMain,
  },
  data() {
    return {
      //2.目标：铺设代办任务
      //2.0-准备数据
      // list: [
      //   { id: 100, name: '吃饭', isDone: true },
      //   { id: 201, name: '睡觉', isDone: false },
      //   { id: 103, name: '打豆豆', isDone: true },
      // ],
      //8.1.取本地存储的数据
      list:JSON.parse(localStorage.getItem('todoList')) ||[],
      //6.4 先中转接收类型字符串
      getSel:"all"//默认显示全部
    }
  },
  methods: {
    //添加任务
    //3.3push到数组里--isDone因为新添加都是未完成的
    createFn(task) {
      let id =
        this.list.length == 0 ? 100 : this.list[this.list.length - 1].id + 1
      this.list.push({
        id: id,
        name: task,
        isDone: false,
      })
    },
    //4.2删除任务-拿到子页面的id
    delFn(id){
      console.log(id);
      let index=this.list.findIndex(item=>item.id===id)
      this.list.splice(index,1)
    },
    typeFn(str){//str有可能是all，yes，no
     this.getSel=str
    },
    clearFn(){//7.1清空已完成--找到未完成的显示出来--过滤未完成的覆盖list数组(不考虑恢复)
    this.list= this.list.filter(item=>item.isDone==false
    )
  },
  },
  
  //6.5定义showArr数组-通过list配合条件筛选而来
  computed:{
    showArr(){
      if(this.getSel==='yes'){
        return this.list.filter(item=>item.isDone===true)
      }else if(this.getSel==='no'){
         return this.list.filter(item=>item.isDone===false)
      }else{
        return this.list//直接全部显示
      }
    }
  },
  //8.目标：数据缓存
  watch:{
    list:{
      deep:true,
      handler(){
        //8.0只要监听到list发生变化-覆盖式的保存到localStrorage
        localStorage.setItem('todoList',JSON.stringify(this.list))
      }
    }
  }
}
</script>

<style></style>
